package netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class MyChannelHandler extends ChannelInboundHandlerAdapter {

    public static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    @Override
    public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
        System.out.println("服务器接收到【" + ctx.channel().remoteAddress() + "】的消息：" + msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("服务器接收到【" + ctx.channel().remoteAddress() + "】的连接");
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //把每个连接过来的客户端添加到 ChannelGroup 中，用于消息群发
        group.add(ctx.channel());
        super.handlerAdded(ctx);

    }
}